package com.szml.user.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;

import java.util.Calendar;

/**
 * @Author limin
 * @date 2025-06-19 18:57
 * @description
 */
public class JWTUtils {
    //密钥
    private static final String secret = "$%2esarqw$#";

    /**
     * 生成token  header.payload.signature
     * @param
     * @param password
     * @return
     */
    public static String getToken(Long userId,String username,String password){
        Calendar instance = Calendar.getInstance();  //日历
        instance.add(Calendar.DATE, 7);//默认7天过期

        String token = JWT.create().withExpiresAt(instance.getTime()) //指定过期时间
                .withClaim("userId", userId)
                .withClaim("username", username)
                .withClaim("password",password)
                .sign(Algorithm.HMAC256(secret));  //signature签名（由密钥经过签名算法生成签名）
        return token;
    }

    /**
     * 验证token
     * @param token
     * @return
     */
    public static Long verify(String token) {
        try {
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7); //给Authorization: Bearer <token>的前缀去掉
            }
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userId").asLong();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取token中的userId
     * @param token
     * @return
     */
    public static Long getUserId(String token) {
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); //给Authorization: Bearer <token>的前缀去掉
        }
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userId").asLong();
        } catch (JWTDecodeException e) {
            return null;
        }
    }
}
